<?php

namespace app\erp\controller;

use app\erp\model\Baojiadb;
use app\erp\model\Goodsdb;
use app\erp\model\GoodsPriceLogdb;
use app\erp\model\JunApiResultdb;
use app\erp\model\Sitedb;
use app\erp\model\TljPushLogdb;
use app\erp\validate\Goodsrule;
use think\Db;
use app\erp\model\Categorydb;
use app\erp\model\Branddb;
use app\erp\model\Attrdb;
use app\erp\model\SalePricedb;
use app\api\controller\Henan;
use app\api\controller\Neimeng;
use app\api\controller\Qixin;
use app\jun\controller\Api;
use app\erp\model\Junapidb;
use think\Cache;
use function GuzzleHttp\Psr7\str;

class Goods extends Base
{
    protected $db;
    protected $cols = array(
        array(
            'field' => 'goods_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'goods_id',
            'width' => 100,
            'title' => 'ID',
            'hide' => 'true'
        ),
        array(
            'field' => 'category_name',
            'width' => 120,
            'title' => '分类',
            'sort' => true
        ),
        array(
            'field' => 'brand_name',
            'width' => 100,
            'title' => '品牌',
            'sort' => 'true'
        ),
        array(
            'field' => 'goods_picture',
            'width' => 80,
            'title' => '封面',
            'templet' => '#goods_picturesTpl'
        ),
        array(
            'field' => 'faburen',
            'width' => 120,
            'title' => '发布人'
        ),
        array(
            'field' => 'view_stock',
            'width' => 60,
            'title' => '库存'
        ),
        array(
            'field' => 'goods_sku',
            'width' => 180,
            'title' => '商品编号'
        ),
        array(
            'field' => 'jun_id',
            'width' => 120,
            'title' => '军网编号'
        ),
        array(
            'field' => 'goods_name',
            'width' => 300,
            'title' => '商品名称',
            'sort' => 'true'
        ),
        array(
            'field' => 'goods_model',
            'width' => 200,
            'title' => '商品型号'
        ),
        array(
            'field' => 'create_time',
            'width' => 120,
            'title' => '发布时间'
        ),
        array(
            'field' => 'goods_unit',
            'width' => 100,
            'title' => '商品单位'
        ),
        array(
            'field' => 'market_price',
            'width' => 100,
            'title' => '市场价'
        ),
        array(
            'field' => 'sale_price',
            'width' => 100,
            'title' => '售价'
        ),
        array(
            'field' => 'api_price',
            'width' => 100,
            'title' => '接口价'
        ),
        array(
            'field' => 'sale_state',
            'width' => 80,
            'title' => '销售',
            'templet' => '#sale_stateTpl'
        ),
//			array (
//					'field' => 'remark',
//					'width' => 80,
//					'title' => '驳回原因',
//			),
        array(
            'field' => 'audit_state',
            'width' => 80,
            'title' => '泰龙吉审核',
            'templet' => '#audit_stateTpl'
        ),
        array(
            'field' => 'jun_state',
            'width' => 80,
            'title' => '军网审核',
            'templet' => '#jun_stateTpl'
        ),
        array(
            'field' => 'details',
            'width' => 160,
            'title' => '驳回内容'
        ),

        array(
            'fixed' => 'right',
            'width' => 150,
            'toolbar' => '#goods_tool',
            'title' => '操作'
        )
    );
    protected $cols_jun = array(
        array(
            'field' => 'goods_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'goods_id',
            'width' => 100,
            'title' => 'ID',
            'hide' => 'true'
        ),
        array(
            'fixed' => 'left',
            'width' => 80,
            'toolbar' => '#goods_jun_tool',
            'title' => '操作'
        ),
        array(
            'field' => 'category_name',
            'width' => 90,
            'title' => '分类',
            'templet' => '#category_nameTpl'
        ),
        array(
            'field' => 'jun_brand_name',
            'width' => 100,
            'title' => '品牌',
            'templet' => '#jun_brand_nameTpl'
        ),
        array(
            'field' => 'goods_picture',
            'width' => 80,
            'title' => '封面',
            'templet' => '#goods_picture2Tpl'
        ),
        array(
            'field' => 'beizhu',
            'width' => 200,
            'title' => '运营备注二'

        ),
        array(
            'field' => 'jun_id',
            'width' => 110,
            'title' => '军采编号',
            'templet' => '#jun_idTpl'
        ),

        array(
            'field' => 'goods_name',
            'width' => 300,
            'title' => '商品名称',
            'templet' => '#goods_nameTpl'
        ),
        array(
            'field' => 'zuidijia',
            'width' => 100,
            'title' => '最低价',
            'templet' => '#zuidijiaTpl'
        ),
        array(
            'field' => 'jun_zuidijia',
            'width' => 100,
            'title' => '展示最低价',
            'templet' => '#jun_zuidijiaTpl'
        ),
        array(
            'field' => 'sale_price',
            'width' => 100,
            'title' => '限价',
            'sort' => true,
            'templet' => '#sale_priceTpl'
        ),
        array(
            'field' => 'api_price',
            'width' => 100,
            'title' => '报价',
            'sort' => true,
            'templet' => '#api_priceTpl'
        ),

        array(
            'field' => 'caigoujia',
            'width' => 100,
            'title' => '厂家成本',
            'templet' => '#caigoujiaTpl'


        ),
        array(
            'field' => 'chengbenjia',
            'width' => 200,
            'title' => '运营备注一'

        ),
        array(
            'field' => 'goods_sku',
            'width' => 100,
            'title' => '商品编号',
            'templet' => '#goods_skuTpl'
        ),
        array(
            'field' => 'goods_id',
            'width' => 80,
            'title' => 'id'

        ),
        array(
            'field' => 'create_time',
            'width' => 120,
            'title' => '发布时间',
            'templet' => '#create_timeTpl'
        ),
        array(
            'field' => 'is_lock',
            'width' => 90,
            'title' => '锁定状态',
            'templet' => '#is_lockTpl'
        ),
        array(
            'field' => 'sale_state',
            'width' => 90,
            'title' => '军采状态',
            'templet' => '#sale_stateTpl'
        ),
        array(
            'field' => 'jun_price_flag',
            'width' => 90,
            'title' => '价格变动',
            'templet' => '#jun_price_flagTpl'
        ),

        array(
            'field' => 'price_warm',
            'width' => 90,
            'title' => '报价警告',
            'templet' => '#price_warmTpl'
        ),
        array(
            'field' => 'is_push',
            'width' => 90,
            'title' => '是否报价',
            'templet' => '#is_pushTpl'
        ),
        array(
            'field' => 'view_stock',
            'width' => 60,
            'title' => '库存'
        ),
        array(
            'field' => 'yybz',
            'width' => 160,
            'title' => '授权备注'
        )
    );
    protected $cols_copy = array(
        array(
            'field' => 'goods_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'category_name',
            'width' => 160,
            'title' => '分类',
            'sort' => true
        ),
        array(
            'field' => 'brand_name',
            'width' => 100,
            'title' => '品牌',
            'sort' => 'true'
        ),
        array(
            'field' => 'goods_picture',
            'width' => 80,
            'title' => '封面',
            'templet' => '#goods_pictureTpl'
        ),
        array(
            'field' => 'goods_sku',
            'width' => 120,
            'title' => '商品编号'
        ),
        array(
            'field' => 'goods_name',
            'width' => 300,
            'title' => '商品名称',
            'sort' => 'true'
        ),
        array(
            'field' => 'goods_model',
            'width' => 200,
            'title' => '商品型号'
        ),
        array(
            'field' => 'market_price',
            'width' => 100,
            'title' => '市场价'
        ),
        array(
            'field' => 'sale_price',
            'width' => 100,
            'title' => '售价'
        ),
        array(
            'field' => 'is_real',
            'width' => 100,
            'title' => '实物',
            'hide' => true,
            'templet' => '#is_realTpl'
        ),
        array(
            'field' => 'is_shopping',
            'width' => 100,
            'title' => '包邮',
            'hide' => true,
            'templet' => '#is_shoppingTpl'
        ),
        array(
            'field' => 'weight',
            'width' => 100,
            'hide' => true,
            'title' => '重量(克)'
        ),
        array(
            'field' => 'view_times',
            'width' => 100,
            'title' => '浏览量',
            'sort' => 'true'
        ),
        array(
            'field' => 'sale_num',
            'width' => 100,
            'title' => '销量',
            'sort' => 'true'
        ),
        array(
            'field' => 'is_install',
            'width' => 80,
            'title' => '安装',
            'templet' => '#is_installTpl'
        ),
        array(
            'field' => 'sale_state',
            'width' => 80,
            'title' => '销售',
            'templet' => '#sale_stateTpl'
        )
    );
    public $post = array();

    public function _initialize()
    {
        parent::_initialize();
        $request = request();
        $param = $request->param();
        $this->post = $param;
        $this->db = new Goodsdb ();
        $this->db->param = $this->post;
    }

    // 推送内蒙商品
    public function pushNeimengInfo($goods_sku)
    {
        $neimengapi = new Neimeng ();
        $this->db->param ['goods_sku'];
        $get_goods = $this->db->ajaxFind();
        $return = $neimengapi->sendGoods($get_goods);
        $this->db->ajaxSaveOne('api_option', json_encode($return));
        $this->db->ajaxsaveOne('out_goods_sku', $return ['goodsguid']);
        echo '商品推送成功';
    }

    // 推送齐心内蒙商品
    public function pushQixinInfo($goods_sku)
    {
        $qixinapi = new Qixin ();
        $this->db->param ['goods_sku'];
        $get_goods = $this->db->ajaxFind();
        $return = $qixinapi->sendGoods($get_goods);
        $this->db->ajaxSaveOne('api_option', json_encode($return));
        $this->db->ajaxsaveOne('out_goods_sku', $return ['goodsguid']);
        echo '商品推送成功';
    }

    // 推送河南商品价格
    public function pushHenanPrice($goods_sku)
    {
        $henanapi = new Henan ();
        $this->db->param ['goods_sku'];
        $get_goods = $this->db->ajaxFind();
        $henanapi->sendGoodsPrice($get_goods);
        echo '报价完成<br />下面是测试信息，以后屏蔽，调试使用：<br />';
        echo '<a target="_blank" href="' . url('pushHenanOther', array(
                'goods_sku' => $goods_sku,
                'mothed' => 'getGoodsInfo'
            )) . '">商品信息</a><br />';
        echo '<a target="_blank" href="' . url('pushHenanOther', array(
                'goods_sku' => $goods_sku,
                'mothed' => 'getGoodsPrice'
            )) . '">单个商品报价</a><br />';
        echo '<a target="_blank" href="' . url('pushHenanOther', array(
                'goods_sku' => $goods_sku,
                'mothed' => 'channelPrice'
            )) . '">取消报价</a><br />';
    }

    // 推送河南其他信息
    public function pushHenanOther($goods_sku, $mothed)
    {
        $henanapi = new Henan ();
        $this->db->param ['goods_sku'];
        $get_goods = $this->db->ajaxFind();
        switch ($mothed) {
            case 'getGoodsInfo' :
                $henanapi->getGoodsInfo($get_goods);
                echo '<br />商品信息获取完成<br />';
                break;
            case 'getGoodsPrice' :
                $henanapi->getGoodsPrice($get_goods);
                echo '<br />商品报价获取完成<br />';
                break;
            case 'channelPrice' :
                $henanapi->channelPrice($get_goods);
                echo '<br />撤销商品报价完成<br />';
                break;
        }
    }

    /**
     * Title("商品价格日志")
     */
    public function priceLog($goods_sku)
    {
        $goodsPriceDb = new GoodsPriceLogdb();
        $get_log = $goodsPriceDb->where('goods_sku', $goods_sku)->order('id desc')->select();
        $this->assign('data', $get_log);
        return $this->fetch();
    }

    public function copy($select_site_id = '')
    {
        $categorydb = new Categorydb ();
        $category_all_sign = $categorydb->ajaxAllSign($select_site_id, 3);
        $category_sign_arr = array();
        foreach ($category_all_sign as $key => $val) {
            array_push($category_sign_arr, $val ['category_sign']);
        }
        $this->assign('category_sign_arr', implode(',', $category_sign_arr));
        $this->assign('select_site_id', $select_site_id);
        $this->assign('cols', json_encode($this->cols_copy));
        return $this->fetch();
    }

    public function collect($select_site_id = '')
    {
        $categorydb = new Categorydb ();
        $category_all_sign = $categorydb->ajaxAllSign($select_site_id, 3);
        $category_sign_arr = array();
        foreach ($category_all_sign as $key => $val) {
            array_push($category_sign_arr, $val ['category_sign']);
        }
        $this->assign('category_sign_arr', implode(',', $category_sign_arr));
        $this->assign('cols', json_encode($this->cols_copy));
        $this->assign('select_site_id', $select_site_id);
        return $this->fetch();
    }

    public function saveCopy()
    {
        if (!isset ($this->post ['goods_sku']) || count($this->post ['goods_sku']) == 0) {
            $this->layuiReturn('请选择要同步的商品');
        }
        if (SITE_ID == null && $this->post ['select_site_id'] == '') {
            $this->layuiReturn('请选择要同步的分站');
        }
        set_time_limit(800);
        Db::startTrans();
        $goodsdb = new Goodsdb ();
        $goodsdb->param ['site_id'] = 0;
        $goodsdb->param ['select_site_id'] = $this->post ['select_site_id'];
        $goodsdb->param ['sale_state'] = 1;
        $goodsdb->param ['is_copy'] = 1;
        $goodsdb->param ['audit_state'] = 1;
        $goodsdb->param ['goods_sku'] = $this->post ['goods_sku'];
        $goodsdb->copy();
        Db::commit();
        $this->layuiReturn('数据同步成功', '', '数据同步成功', 1);
    }

    public function saveCollect()
    {
        if (!isset ($this->post ['goods_sku']) || count($this->post ['goods_sku']) == 0) {
            $this->layuiReturn('请选择要采集的商品');
        }
        if (SITE_ID == null && $this->post ['select_site_id'] == '') {
            $this->layuiReturn('请选择要采集的分站');
        }
        set_time_limit(800);
        Db::startTrans();
        $goodsdb = new Goodsdb ();
        $goodsdb->param ['site_id'] = $this->post ['select_site_id'];
        $goodsdb->param ['select_site_id'] = 0;
        $goodsdb->param ['goods_sku'] = $this->post ['goods_sku'];
        $goodsdb->collect();
        Db::commit();
        $this->layuiReturn('数据采集成功', '', '数据采集成功', 1);
    }

    public function index()
    {
        $this->assign('cols', json_encode($this->cols));
        // 获取分站信息
        $sitedb = new Sitedb ();
        $get_site = $sitedb->ajaxFind(SITE_ID);
        $this->assign('get_site', $get_site);
        $this->assign('site_id', SITE_ID);
        // 获取分站列表
        $sitedb->param ['_o'] = 'site_id';
        $sitedb->param ['_b'] = 'asc';
        $sitedb->param ['page'] = 1;
        $sitedb->param ['limit'] = 1000;
        $get_site_list = $sitedb->ajaxSelect();
        $this->assign('site_list', $get_site_list ['data']);
        return $this->fetch();
    }

    public function jun()
    {
        if (!in_array(MEMBER_ID, [207, 193, 495, 203, 496, 217, 623, 218, 486, 379, 208, 209, 494, 210, 216, 212, 10431])) {
            foreach ($this->cols_jun as $key => $val) {
                if (isset($val['field']) && in_array($val['field'], ['caigoujia', 'chengbenjia', 'zuidijia', 'jun_zuidijia'])) {
                    unset($this->cols_jun[$key]);
                }
            }
        }
        $this->assign('cols', json_encode($this->cols_jun));
        // 获取分站信息
        $sitedb = new Sitedb ();
        $get_site = $sitedb->ajaxFind(SITE_ID);
        $this->assign('get_site', $get_site);
        $this->assign('site_id', SITE_ID);
        // 获取分站列表
        $sitedb->param ['_o'] = 'site_id';
        $sitedb->param ['_b'] = 'asc';
        $sitedb->param ['page'] = 1;
        $sitedb->param ['limit'] = 1000;
        $get_site_list = $sitedb->ajaxSelect();
        $this->assign('site_list', $get_site_list ['data']);
        return $this->fetch();
    }

    public function tplForm()
    {
        // 获取分站信息
        $sitedb = new Sitedb ();
        $get_site = $sitedb->ajaxFind(SITE_ID);
        $this->assign('get_site', $get_site);
        $goods_sign = 0;
        $data = array();
        $data = $this->db->ajaxFind();
        $this->assign('data', json_encode($data));
        $goods_sign = $data ['goods_sku'];
        $this->assign('goods_sign', $goods_sign);
        $goods_id = isset ($data ['goods_id']) ? $data ['goods_id'] : '';
        $this->assign('goods_id', $goods_id);
        if (SITE_ID == 10) {
            // 河南的单独处理
            return $this->fetch('goods/tpl_form_henan');
            exit ();
        }
        return $this->fetch();
    }

    public function tplFormJun()
    {
        // 获取分站信息
        $sitedb = new Sitedb ();
        $get_site = $sitedb->ajaxFind(SITE_ID);
        $this->assign('get_site', $get_site);
        $goods_sign = 0;
        $data = array();
        $this->db->param ['pre_info'] = 'jun';
        $data = $this->db->ajaxFind();
        $this->assign('data', json_encode($data));
        $this->assign('goods_data', $data);
        $goods_sign = $data ['goods_sku'];
        $this->assign('goods_sign', $goods_sign);
        $goods_id = isset ($data ['goods_id']) ? $data ['goods_id'] : '';
        $this->assign('goods_id', $goods_id);
        $is_lock = isset ($data ['is_lock']) ? $data ['is_lock'] : '';
        $this->assign('is_lock', $is_lock);

        // 是否验证地区
        $check_area = $data['check_area'];
        $this->assign('check_area', $check_area);
        return $this->fetch();
    }

    public function ajaxList($pre_info = '')
    {
        $this->db->param ['no_more_price'] = 'yes';
        $this->db->param ['pre_info'] = $pre_info;
        $this->db->param ['lastbaojia'] = 'yes';
        $return = $this->db->ajaxSelect();
        $this->layuiReturn($return ['data'], $return ['count']);
    }

    public function ajaxCopyList()
    {
        $this->db->param ['site_id'] = 0;
        $this->db->param ['no_more_price'] = 'yes';
        $return = $this->db->ajaxSelect();
        $this->layuiReturn($return ['data'], $return ['count']);
    }

    public function ajaxCollectList()
    {
        if (isset ($this->db->param ['master_no'])) {
            $temp = explode(',', $this->db->param ['category_sign3']);
            if (count($temp) > 1) {
                $this->layuiReturn('请选择到三级分类', 0, '请选择到三级分类', -1);
            }
        }
        $this->db->param ['no_more_price'] = 'yes';
        $return = $this->db->ajaxSelect();
        $this->layuiReturn($return ['data'], $return ['count']);
    }

    /**
     * @同步商品状态
     */
    public function implodeGoodsComm()
    {
        set_time_limit(0);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $get_col_num = $sheet->getHighestColumn(); // 总列
                $phpexcel_shared_date = new \PHPExcel_Shared_Date ();
                $data = array();
                $text = '';
                $the_sheet = $objPHPExcel->getActiveSheet();
                $goodsdb = new Goodsdb();
                $salePricedb = new SalePricedb();
                // 验证文档模板是否正确
                if ($this->getSheetValue($the_sheet, "O1") != '锁定（1是锁定2是不锁定）') {
                    $this->layuiReturn($data, 0, '文档格式不对', 0);
                }
                for ($i = 2; $i <= $get_row_num; $i++) {
                    $temp ['goods_sku'] = trim($this->getSheetValue($the_sheet, "A" . $i));
                    $get_goods = $goodsdb->where('goods_sku', $temp['goods_sku'])->find();
                    if ($get_goods) {
                        $save_goods = [];
                        $sale_attr = [];
                        //   if (trim($this->getSheetValue($the_sheet, "B" . $i)))
                        //        $save_goods['goods_name'] = trim($this->getSheetValue($the_sheet, "B" . $i));
                        if (trim($this->getSheetValue($the_sheet, "C" . $i)))
                            $save_goods['upc'] = trim($this->getSheetValue($the_sheet, "C" . $i));
                        if (trim($this->getSheetValue($the_sheet, "D" . $i)))
                            $save_goods['goods_son_name'] = trim($this->getSheetValue($the_sheet, "D" . $i));
                        if (trim($this->getSheetValue($the_sheet, "E" . $i)))
                            $save_goods['product_firm'] = trim($this->getSheetValue($the_sheet, "E" . $i));
                        if (trim($this->getSheetValue($the_sheet, "F" . $i)))
                            $save_goods['invoice_model'] = trim($this->getSheetValue($the_sheet, "F" . $i));
                        if (trim($this->getSheetValue($the_sheet, "G" . $i)))
                            $save_goods['goods_unit'] = trim($this->getSheetValue($the_sheet, "G" . $i));
                        if (trim($this->getSheetValue($the_sheet, "H" . $i)))
                            $save_goods['product_area'] = trim($this->getSheetValue($the_sheet, "H" . $i));
                        if (trim($this->getSheetValue($the_sheet, "I" . $i)))
                            $save_goods['shuiwu_id'] = trim($this->getSheetValue($the_sheet, "I" . $i));
                        if (trim($this->getSheetValue($the_sheet, "J" . $i)))
                            $save_goods['goods_keywords'] = trim($this->getSheetValue($the_sheet, "J" . $i));
                        if (trim($this->getSheetValue($the_sheet, "K" . $i)) != '')
                            $sale_attr['zuidijia'] = trim($this->getSheetValue($the_sheet, "K" . $i));
                        if (trim($this->getSheetValue($the_sheet, "L" . $i)) != '')
                            $sale_attr['caigoujia'] = trim($this->getSheetValue($the_sheet, "L" . $i));
                        if (trim($this->getSheetValue($the_sheet, "M" . $i)) != '')
                            $sale_attr['chengbenjia'] = trim($this->getSheetValue($the_sheet, "M" . $i));
                        if (trim($this->getSheetValue($the_sheet, "N" . $i)))
                            $sale_attr['beizhu'] = trim($this->getSheetValue($the_sheet, "N" . $i));
                        if (trim($this->getSheetValue($the_sheet, "O" . $i)))
                            $save_goods['is_lock'] = trim($this->getSheetValue($the_sheet, "O" . $i));
                        if (trim($this->getSheetValue($the_sheet, "P" . $i)))
                            $save_goods['goods_beizhu1'] = trim($this->getSheetValue($the_sheet, "P" . $i));
                        if (trim($this->getSheetValue($the_sheet, "Q" . $i)))
                            $save_goods['goods_beizhu2'] = trim($this->getSheetValue($the_sheet, "Q" . $i));
                        if (trim($this->getSheetValue($the_sheet, "R" . $i)))
                            $save_goods['goods_beizhu3'] = trim($this->getSheetValue($the_sheet, "R" . $i));
                        if (trim($this->getSheetValue($the_sheet, "S" . $i)))
                            $save_goods['goods_beizhu4'] = trim($this->getSheetValue($the_sheet, "S" . $i));
                        if (trim($this->getSheetValue($the_sheet, "T" . $i)))
                            $save_goods['goods_beizhu5'] = trim($this->getSheetValue($the_sheet, "T" . $i));
                        if (trim($this->getSheetValue($the_sheet, "U" . $i)))
                            $save_goods['goods_beizhu6'] = trim($this->getSheetValue($the_sheet, "U" . $i));
                        if (trim($this->getSheetValue($the_sheet, "V" . $i)))
                            $save_goods['code_69'] = trim($this->getSheetValue($the_sheet, "V" . $i));
                        $save_goods['check_area'] = 0;
                        if (trim($this->getSheetValue($the_sheet, "W" . $i)))
                            $save_goods['check_area'] = trim($this->getSheetValue($the_sheet, "W" . $i));
                        $save_goods['zhenshi'] = 0;
                        if (trim($this->getSheetValue($the_sheet, "X" . $i)))
                            $save_goods['zhenshi'] = trim($this->getSheetValue($the_sheet, "X" . $i));
                        if (trim($this->getSheetValue($the_sheet, "Y" . $i)))
                            $save_goods['goods_beizhu8'] = trim($this->getSheetValue($the_sheet, "Y" . $i));
                        if (trim($this->getSheetValue($the_sheet, "Z" . $i)))
                            $save_goods['goods_beizhu9'] = trim($this->getSheetValue($the_sheet, "Z" . $i));
                        if (trim($this->getSheetValue($the_sheet, "AA" . $i)))
                            $save_goods['goods_beizhu10'] = trim($this->getSheetValue($the_sheet, "AA" . $i));
                        if (trim($this->getSheetValue($the_sheet, "AB" . $i)))
                            $save_goods['goods_beizhu11'] = trim($this->getSheetValue($the_sheet, "AB" . $i));
                        if (trim($this->getSheetValue($the_sheet, "AC" . $i)))
                            $save_goods['goods_beizhu12'] = trim($this->getSheetValue($the_sheet, "AC" . $i));
                        if (trim($this->getSheetValue($the_sheet, "AD" . $i)))
                            $save_goods['goods_beizhu13'] = trim($this->getSheetValue($the_sheet, "AD" . $i));
                        if (trim($this->getSheetValue($the_sheet, "AE" . $i)))
                            $save_goods['goods_beizhu14'] = trim($this->getSheetValue($the_sheet, "AE" . $i));
                        if (trim($this->getSheetValue($the_sheet, "AF" . $i)))
                            $save_goods['goods_beizhu15'] = trim($this->getSheetValue($the_sheet, "AF" . $i));
                        if (trim($this->getSheetValue($the_sheet, "AG" . $i)))
                            $save_goods['goods_beizhu7'] = trim($this->getSheetValue($the_sheet, "AG" . $i));    
                        if (count($save_goods) > 0) {
                            $get_goods->save($save_goods);
                        }
                        if (count($sale_attr) > 0) {
                            $get_price = $salePricedb->where('goods_sku', $temp ['goods_sku'])->order('create_time', 'desc')->find();
                            if ($get_price) {
                                $get_price->save($sale_attr);
                            }
                        }
                    }

                }
                Cache::clear('goods');
                Cache::clear('sale_price');
                $this->layuiReturn($data, 0, '导入成功', 1);
            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
            }
        }
    }

    /**
     * @同步军网报价
     */
    public function junBaojia()
    {
        set_time_limit(0);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $data = array();
                $the_sheet = $objPHPExcel->getActiveSheet();
                for ($i = 2; $i <= $get_row_num; $i++) {
                    $temp = [];
                    $temp ['productguid'] = trim($this->getSheetValue($the_sheet, "A" . $i));
                    $temp ['indicativeprice'] = trim($this->getSheetValue($the_sheet, "B" . $i));
                    $temp ['lowprice'] = trim($this->getSheetValue($the_sheet, "C" . $i));
                    array_push($data, $temp);
                }
                $result = $this->commMinPrice($data);
                $this->layuiReturn($result, 0, $result, 1);
            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
            }
        }
    }


    /**
     * Title("计算最低价推送地址")
     * Url("https://tailongji.dixintong.com/erp/goods/testCalc.html")
     */
    public function testCalc()
    {
        $cankao = '1492.71';
        $zuidi = '1250.3';
        $chengben = '1130';
        $beizhu = '保持最低价（采购部）';
        $sale_price = '1492.71';
        $api_price = 1250.49;
        $stock = 11;
        $result = $this->calcPushPriceStock($cankao, $zuidi, $chengben, $beizhu, $sale_price, $api_price, $stock);
        halt($result);
    }

    /**
     * Title("设置number_format")
     */
    protected function strToFloat($num)
    {
        return number_format($num, 2, '.', '');
    }


    /**
     * Title("计算推送价格和库存")
     */
    protected function calcPushPriceStock($cankao, $zuidi, $chengben, $beizhu, $sale_price, $api_price = 0, $stock = 0)
    {
        $result = [];
        $rate = 0.95;
        $ml = 1.087;
        $ck = 0.55;
        $result['price'] = 0;
        $result['stock'] = 0;
        $result['is_push'] = true;
        if ($cankao > 0) {
            if ($zuidi > 0) {
                if ($chengben > 0) { //A
                    if (stripos($beizhu, '禁止报价') === 0) {
                        $result['step'] = '2';
                        $result['price'] = $cankao;
                        $result['stock'] = 0;
                    }
                    if (stripos($beizhu, '保持不变') === 0) {
                        $result['price'] = $api_price;
                        $result['stock'] = $stock;
                        $result['is_push'] = false;
                        $result['step'] = '3';
                    }
                    if (stripos($beizhu, '保持最低价') === 0) {
                        if ($this->strToFloat($chengben * $ml) <= $this->strToFloat($zuidi)) {
                            if ($this->strToFloat($zuidi) >= $this->strToFloat($cankao * $ck)) {
                                $result['price'] = $zuidi;
                                $result['stock'] = 11;
                                $result['step'] = '4';
                            } else {
                                $result['price'] = $cankao * $ck;
                                $result['stock'] = 9;
                                $result['step'] = '5';
                            }
                        } else {
                            if ($this->strToFloat($chengben * $ml) < $this->strToFloat($cankao * $ck)) {
                                $result['price'] = $cankao * $ck;
                                $result['stock'] = 9;
                                $result['step'] = '6';
                            } else {
                                $result['price'] = $chengben * $ml;
                                $result['stock'] = 10;
                                $result['step'] = '7';
                            }
                        }
                    }
                    if (stripos($beizhu, '空白') === 0) {
                        if ($this->strToFloat($chengben * $ml) <= $this->strToFloat($zuidi)) {
                            if ($this->strToFloat($zuidi) >= $this->strToFloat($cankao * $ck)) {
                                $result['price'] = $zuidi;
                                $result['stock'] = 11;
                                $result['step'] = '8';
                            } else {
                                $result['price'] = $cankao * $ck;
                                $result['stock'] = 9;
                                $result['step'] = '9';
                            }
                        } else {
                            if ($this->strToFloat($chengben * $ml) >= $this->strToFloat($cankao * $ck)) {
                                $result['price'] = $chengben * $ml;
                                $result['stock'] = 10;
                                $result['step'] = '10';
                            } else {
                                $result['price'] = $cankao * $ck;
                                $result['stock'] = 9;
                                $result['step'] = '11';
                            }
                        }
                    }
                } else {//B
                    // 无成本价
                    $result['price'] = $cankao;
                    $result['stock'] = 0;
                    $result['step'] = '12,13,14,15';
                }
            } else {
                // 无最低价
                if ($chengben > 0) {// C
                    if (stripos($beizhu, '空白') === 0 || stripos($beizhu, '保持不变') === 0 || stripos($beizhu, '保持最低价')) {
                        $result['price'] = $cankao * $rate;
                        $result['stock'] = 12;
                        $result['step'] = '17,18,19';
                    } else {
                        $result['price'] = $cankao;
                        $result['stock'] = 0;
                        $result['step'] = '16';
                    }
                } else { // D
                    $result['price'] = $cankao;
                    $result['stock'] = 0;
                    $result['step'] = '20,21,22,23';
                }
            }
        } else {
            $result['price'] = $sale_price;
            $result['stock'] = 0;
            if ($zuidi > 0) {
                if ($chengben > 0) { //E
                    if (stripos($beizhu, '禁止报价') === 0) {
                        $result['price'] = $cankao;
                        $result['stock'] = 0;
                        $result['step'] = '24';
                    }
                    if (stripos($beizhu, '保持不变') === 0) {
                        $result['price'] = $api_price;
                        $result['stock'] = $stock;
                        $result['is_push'] = false;
                        $result['step'] = '25';
                    }
                    if (stripos($beizhu, '保持最低价') === 0 || stripos($beizhu, '空白') === 0) {
                        if ($chengben * $ml <= $zuidi) {
                            $result['price'] = $zuidi;
                            $result['stock'] = 11;
                            $result['step'] = '26,28';
                        } else {
                            $result['price'] = $chengben * $ml;
                            $result['stock'] = 10;
                            $result['step'] = '27,29';
                        }
                    }
                } else { //F
                    $result['price'] = $cankao;
                    $result['stock'] = 0;
                    $result['step'] = '30,31,32,33';
                }
            } else {
                if ($chengben > 0) {//G
                    if (stripos($beizhu, '禁止报价') === 0) {
                        $result['price'] = $cankao;
                        $result['stock'] = 0;
                        $result['step'] = '34';
                    }
                    if (stripos($beizhu, '保持不变') === 0 || stripos($beizhu, '保持最低价') === 0 || stripos($beizhu, '空白') === 0) {
                        $result['price'] = $sale_price * $rate;
                        $result['stock'] = 12;
                        $result['step'] = '35,36,37';
                    }
                } else { //H
                    $result['price'] = $cankao;
                    $result['stock'] = 0;
                    $result['step'] = '38,39,40,41';
                }
            }
        }

        // 禁止报价和空白还有空推送最低价
        if (trim($beizhu) == '' || stripos($beizhu, '禁止报价') === 0 || stripos($beizhu, '空白') === 0 || stripos($beizhu, '改价需报备') === 0 || stripos($beizhu, '保持不变') === 0) {
            $result['is_push'] = false;
        }

        if ($result['is_push'] == true) {
            if ($api_price == $result['price'] && $stock == $result['stock']) {
                $result['is_push'] = false;
            }
        }
        /* if($beizhu == '保持最低价' || $beizhu == '最低价'){
         $result['is_push'] = true;
         } else {
         $result['is_push'] = false;
         }
         */
        return $result;

    }

    /**
     * Title("计算推送价格新版")
     */
    public function commMinPriceNew($sku_data)
    {
        $get_product_list = $sku_data;
        $sku_arr = [];
        $data_arr = [];
        $out_arr = [];
        if (isset($get_product_list)) {
            foreach ($get_product_list as $key => $val) {
                array_push($out_arr, [
                    'productguid' => $val['productguid'],
                    'indicativeprice' => $val['indicativeprice'],
                    'lowprice' => $val['lowprice']
                ]);
                array_push($sku_arr, $val['productguid']);
                $data_arr[$val['productguid']] = array('indicativeprice' => $val['indicativeprice'], 'lowprice' => $val['lowprice']);
            }
            if (count($sku_arr) == 0) {
                // 没有可查询数据  退出
                return 'excel没有数据,请检查格式';
            }

            $salePricedb = new SalePricedb();
            // 默认查询结果是非4情况
            $get_sale_price = $salePricedb
                ->whereIn('goods_sku', $sku_arr)
                ->where('view_stock', '<>', 4)
                ->select();
            $push_data = [];
            $goodsdb = new Goodsdb();
            foreach ($get_sale_price as $key => $val) {
                $price_arr = $data_arr[$val['goods_sku']];
                // 保证最低价和参考价不一致之后报价
                if ((float)$price_arr['lowprice'] != (float)$val['zuidijia'] || (float)$price_arr['indicativeprice'] != (float)$val['sale_price']) {
                    $get_price_stock = $this->calcPushPriceStock((float)$price_arr['indicativeprice'], (float)$price_arr['lowprice'], (float)$val['caigoujia'], $val['beizhu'], (float)$val['sale_price'], (float)$val['api_price'], (int)$val['view_stock']);
                    // 断点打印结果
                    /*print_r($get_price_stock);
                    exit();*/
                    //if ($get_price_stock['stock'] == 0 && $get_price_stock['price'] == 0) {
                    if ($get_price_stock['is_push'] == false) {
                        //$val->save(['zuidijia'=>(float)$price_arr['lowprice']]);
                        // 价格和库存都为0 执行下一条
                        continue;
                    }
                    $temp = [];
                    $temp['sku'] = $val['goods_sku'];
                    $temp['price'] = number_format($get_price_stock['price'], 2, '.', '');
                    $temp['stock'] = $get_price_stock['stock'];

                    $temp['min_price'] = $price_arr['lowprice'];
                    $temp['indicativeprice'] = $price_arr['indicativeprice'];
                    $get_goods = $goodsdb->where('goods_sku', $val['goods_sku'])->field('goods_id')->find();
                    $temp['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $get_goods['goods_id'];
                    $temp['eccode'] = $get_goods['goods_id'];
                    $temp['linkprice'] = $val['sale_price'];
                    $temp['create_date'] = date('Y-m-d H:i:s');
                    array_push($push_data, $temp);
                    $save_data_price = [
                        'zuidijia' => $price_arr['lowprice'],
                        'sale_price' => $price_arr['indicativeprice'],
                        'api_price' => (float)$temp['price'],
                        'view_stock' => $temp['stock']
                    ];
                    //print_r($save_data_price);
                    $val->save($save_data_price);
                }
            }
            if (count($push_data)) {
                $pushLogdb = new TljPushLogdb();
                $pushLogdb->saveAll($push_data);
                // 有推送价格 推送商品
                $new_push_data = [];
                $j = 0;
                $i = 0;
                foreach ($push_data as $k => $v) {
                    $j++;
                    $i++;
                    array_push($new_push_data, $v);
                    if ($j == 100 || $i == count($push_data)) {
                        $this->pushJunPriceExcel($new_push_data);
                        $j = 0;
                        $new_push_data = [];
                    }
                }

            }
        }
        return '完成';
    }

    /**
     * Title("计算推送价格老版")
     */
    public function commMinPrice($sku_data)
    {
        //halt('老');
        $get_product_list = $sku_data;
        $sku_arr = [];
        $data_arr = [];
        $out_arr = [];
        if (isset($get_product_list)) {
            foreach ($get_product_list as $key => $val) {
                array_push($out_arr, [
                    'productguid' => $val['productguid'],
                    'indicativeprice' => $val['indicativeprice'],
                    'lowprice' => $val['lowprice']
                ]);
                array_push($sku_arr, $val['productguid']);
                $data_arr[$val['productguid']] = array('indicativeprice' => $val['indicativeprice'], 'lowprice' => $val['lowprice']);
            }
            if (count($sku_arr) == 0) {
                // 没有可查询数据  退出
                return 'excel没有数据,请检查格式';
            }

            $salePricedb = new SalePricedb();
            $get_sale_price = $salePricedb
                ->whereIn('goods_sku', $sku_arr)
                //->whereNotIn('view_stock', [0,4])
                ->where('view_stock', '<>', 4)
                ->where('caigoujia', '>', 0)
                ->select();
            $rate_price_max = 1.18;
            $rate_price_min = 1.087;
            $max_num = 11;
            $mid_num = 10;
            $min_num = 0;
            $big_num = 12;
            $push_data = [];
            $goodsdb = new Goodsdb();
            foreach ($get_sale_price as $key => $val) {
                $price_arr = $data_arr[$val['goods_sku']];
                // 保证最低价和参考价不一致之后报价
                if ((float)$price_arr['lowprice'] != (float)$val['zuidijia'] || (float)$price_arr['indicativeprice'] != (float)$val['sale_price']) {
                    if (stripos($val['beizhu'], '特殊报价') === 0) {
                        $rate = $rate_price_max;
                    } elseif (stripos($val['beizhu'], '保持最低价') === 0 || stripos($val['beizhu'], '空白') === 0) {
                        $rate = $rate_price_min;
                    } else {
                        $rate = 0;
                    }
                    if ($rate === 0) {
                        continue; // 毛利率则移除,执行下一条
                    }
                    $mid_price = number_format($rate * $val['caigoujia'], 2, '.', '');
                    $temp = [];
                    $temp['sku'] = $val['goods_sku'];

                    if (number_format($mid_price, 2, '.', '') <= number_format($price_arr['lowprice'], 2, '.', '')) {
                        $temp['price'] = $price_arr['lowprice'];
                        $temp['stock'] = $max_num;
                        // 小于最低价
                    } elseif (number_format($mid_price, 2, '.', '') <= number_format($price_arr['indicativeprice'], 2, '.', '')) {
                        // 大于最低价小于参考价
                        $temp['price'] = $mid_price;
                        $temp['stock'] = $mid_num;
                    } else {
                        // 大于参考价
                        $temp['price'] = $price_arr['indicativeprice'];
                        $temp['stock'] = $min_num;
                        if ((float)$price_arr['indicativeprice'] == 0) {
                            $temp['stock'] = $mid_num;
                        }
                    }

                    if ((float)$price_arr['indicativeprice'] == 0 && (float)$price_arr['lowprice'] == 0) {
                        $temp['stock'] = $big_num;
                    }

                    $temp['min_price'] = $price_arr['lowprice'];
                    $temp['indicativeprice'] = $price_arr['indicativeprice'];
                    $get_goods = $goodsdb->where('goods_sku', $val['goods_sku'])->field('goods_id')->find();
                    $temp['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $get_goods['goods_id'];
                    $temp['eccode'] = $get_goods['goods_id'];
                    $temp['linkprice'] = $val['api_price'];
                    array_push($push_data, $temp);
                    $save_data_price = [
                        'zuidijia' => $price_arr['lowprice'],
                        'sale_price' => $price_arr['indicativeprice'],
                        'api_price' => (float)$temp['price'],
                        'view_stock' => $temp['stock']
                    ];
                    $val->save($save_data_price);

                    /*if ($val['sale_price']) {
                        // 有参考价
                        if ($price_arr['lowprice']) {

                        } else {
                            // 没有最低价
                        }
                    } else {
                        // 没有参考价
                    }*/
                }
            }
            if (count($push_data)) {
                // 有推送价格 推送商品
                $new_push_data = [];
                $j = 0;
                $i = 0;
                foreach ($push_data as $k => $v) {
                    $j++;
                    $i++;
                    array_push($new_push_data, $v);
                    if ($j == 100 || $i == count($push_data)) {
                        $this->pushJunPriceExcel($new_push_data);
                        $j = 0;
                        $new_push_data = [];
                    }
                }

            }
            /*file_put_contents('sku_arr.txt', $salePricedb->getLastSql());
            file_put_contents('data_arr.txt', json_encode($push_data));
            file_put_contents('sku_price.txt', json_encode($out_arr));*/
        }
        return '完成';
    }

    public function pushJunPriceExcel($push_data)
    {
        $temp_x1 = $push_data;
        $temp_x2 = [];
        foreach ($temp_x1 as $key => $val) {
            //Db::name('sale_price')->where('goods_sku',$val['sku'])->update(['zuidijia'=>$val['min_price'],'api_price'=>$val['price']]);
            unset($val['min_price']);
            unset($val['indicativeprice']);
            array_push($temp_x2, $val);
        }
        $post_data['priceList'] = $temp_x2;
        $junApid = new Api();
        $result = $junApid->ajaxCountPrice($post_data);
        //file_put_contents('x2.txt', json_encode($result));
        if (isset($result['priceList'])) {
            // 保存推送结果
            $junApiResultdb = new JunApiResultdb();
            $goodsdb = new Goodsdb();
            $save_all = [];
            $log_data = [];
            foreach ($result['priceList'] as $key => $val) {
                $temp_api = [];
                $temp_api['goods_sku'] = $val['skuId'];
                $temp_api['is_success'] = $val['issuccess'] == 'false' ? 0 : 1;
                $temp_api['reason'] = $val['reason'];
                //file_put_contents('x3.txt', json_encode($temp_api));
                $get_goods = $goodsdb->where('goods_sku', $val['skuId'])->find();
                $salePricedb = new SalePricedb();
                $get_sale_price = $salePricedb->where('goods_sku', $val['skuId'])->order('sale_price_id', 'desc')->find();
                $temp_api['sale_price'] = $get_sale_price['sale_price'];
                $temp_api['api_price'] = $get_sale_price['api_price'];
                $temp_api['view_stock'] = $get_sale_price['view_stock'];
                $temp_api['caigoujia'] = $get_sale_price['caigoujia'];
                $temp_api['beizhu'] = $get_sale_price['beizhu'];
                $temp_api['zuidijia'] = $get_sale_price['zuidijia'];
                array_push($save_all, $temp_api);

                $temp['goods_sku'] = $val['skuId'];
                $temp['date'] = date('Y-m-d H:i:s');
                $temp['types'] = '同步军网报价';
                $temp_son = [];
                $temp_son['用户'] = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
                $temp_son['参考价'] = $temp_api['sale_price'];
                $temp_son['成本'] = $temp_api['caigoujia'];
                $temp_son['报价'] = $get_sale_price['api_price'];
                $temp_son['真实库存'] = $get_goods['zhenshi'];
                $temp_son['最低价'] = $temp_api['zuidijia'];
                $temp_son['库存'] = $temp_api['view_stock'];
                $temp_son['结果'] = $val['reason'];
                $temp['params'] = json_encode($temp_son, JSON_UNESCAPED_UNICODE);
                array_push($log_data, $temp);
                if ($get_goods) {
                    $get_goods->save(['push_jun_state' => $val['issuccess'] == 'false' ? 2 : 1]);
                }
            }
            $junApiResultdb->saveAll($save_all);

            $goodsPriceDb = new GoodsPriceLogdb();
            $goodsPriceDb->saveAll($log_data);
        }
    }

    /**
     * Title("导入报价单")
     */
    public function implodeJunXml()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $get_col_num = $sheet->getHighestColumn(); // 总列
                $phpexcel_shared_date = new \PHPExcel_Shared_Date ();
                $data = array();
                $text = '';
                $the_sheet = $objPHPExcel->getActiveSheet();
                for ($i = 2; $i <= $get_row_num; $i++) {
                    $get_goods = Goodsdb::where('goods_sku', $this->getSheetValue($the_sheet, "A" . $i))->find();
                    unset ($temp);
                    if ($get_goods) {
                        $temp ['goods_sku'] = $this->getSheetValue($the_sheet, "A" . $i);
                        $temp ['goods_name'] = $this->getSheetValue($the_sheet, "B" . $i);
                        $temp ['sale_price'] = number_format($this->getSheetValue($the_sheet, "C" . $i), 2, '.', '');
                        $temp ['api_price'] = number_format($this->getSheetValue($the_sheet, "D" . $i), 2, '.', '');
                        $temp ['view_stock'] = $this->getSheetValue($the_sheet, "E" . $i);
                        $temp ['sale_state'] = 1;
                        $temp ['audit_state'] = 1;
                        $temp ['goods_id'] = '';
                        $temp ['jun_id'] = $get_goods['jun_id'];
                        $baojiadb = new Baojiadb();
                        $get_baojia = $baojiadb->where('goods_id', $get_goods['goods_id'])->order('baojia_id', 'desc')->value('create_time');
                        $temp ['lastbaojia'] = $get_baojia ? date('Y-m-d H:i', $get_baojia) : '';
                        // 校验今日是否报价
                        $chk_log = Db::name('goods_price_log')
                            //->fetchSql(true)
                            ->where('goods_sku', $get_goods['goods_sku'])
                            ->whereIn('types', ['供应商报价', '军采统一报价', '产品详情报价', '同步军网报价', '报价审核', '自动推送下架'])
                            ->whereTime('date', 'today')
                            ->whereLike('params', '%"结果":"入库成功"%')
                            ->group('goods_sku')
                            ->count();
                        if ($chk_log > 0) {
                            $temp['is_lock'] = 3;
                        }
                        // 校验结束
                        array_push($data, $temp);
                    }
                }
                if (count($data) > 100) {
                    $this->layuiReturn('导入报价不能超过100条', 0, '导入报价不能超过100条', 0);
                }
                if (count($data) > 0) {
                    $this->layuiReturn($data, 0, '导入成功', 1);
                } else {
                    $this->layuiReturn('导入失败', 0, '没有数据', 0);
                }
            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
            }
        }
    }

    public function saveCgGood()
    {
        if (!isset($this->post['goods_sku_arr'])) {
            $this->layuiReturn('请先导入报价单', 0, '请先导入报价单', 2);
        }
        // 验证sku是否和商品名称一致
        $log_data = [];
        $username = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
        for ($i = 0; $i < count($this->post ['goods_sku_arr']); $i++) {
            $getGoods = $this->db->useGlobalScope(false)->where('goods_sku', $this->post ['goods_sku_arr'] [$i])->find();
            if ($getGoods) {
                if (str_replace(' ', '', $getGoods['goods_name']) != str_replace(' ', '', $this->post['goods_name_arr'][$i])) {
                    $this->layuiReturn($this->post ['goods_sku_arr'] [$i] . ':不能与商品名称匹配', 0, $this->post ['goods_sku_arr'] [$i] . ':不能与商品名称匹配', 2);
                }
            } else {
                $this->layuiReturn($this->post ['goods_sku_arr'] [$i] . ':编号错误', 0, $this->post ['goods_sku_arr'] [$i] . ':编号错误', 2);
            }

            $get_price = Db::name('sale_price')->where('goods_sku', $this->post ['goods_sku_arr'] [$i])->field('zuidijia,caigoujia')->find();

            $temp = [];
            $temp['goods_sku'] = $this->post ['goods_sku_arr'] [$i];
            $temp['date'] = date('Y-m-d H:i:s');
            $temp['types'] = '军采统一报价';
            $temp_son = [];
            $temp_son['用户'] = $username;
            $temp_son['参考价'] = $this->post ['sale_price_arr'] [$i];
            $temp_son['报价'] = $this->post['api_price_arr'][$i];
            $temp_son['成本'] = $get_price['caigoujia'];
            $temp_son['库存'] = $this->post['view_stock_arr'][$i];
            $temp_son['真实库存'] = $getGoods['zhenshi'];
            $temp_son['最低价'] = $get_price['zuidijia'];
            $temp['params'] = json_encode($temp_son, JSON_UNESCAPED_UNICODE);
            array_push($log_data, $temp);
        }
        // 先处理价格表的数据
        $salePricedb = new SalePricedb ();
        $post_jun['priceList'] = array();
        for ($i = 0; $i < count($this->post ['goods_sku_arr']); $i++) {
            $salePricedb->useGlobalScope(false)->where('goods_sku', $this->post ['goods_sku_arr'] [$i])->update(array(
                'api_price' => $this->post ['api_price_arr'] [$i],
                'view_stock' => $this->post ['view_stock_arr'] [$i]
            ));
            $get_post = $this->junPush($this->post ['goods_sku_arr'] [$i], $this->post ['api_price_arr'] [$i], $this->post ['view_stock_arr'] [$i]);
            array_push($post_jun['priceList'], $get_post['priceList'][0]);
        }
        $jun_api = new Api ();
        $result = $jun_api->ajaxCountPrice($post_jun);

        $priceLogDb = new GoodsPriceLogdb();
        foreach ($log_data as $key => $val) {
            $params = json_decode($val['params'], true);
            foreach ($result['priceList'] as $k => $v) {
                if ($v['skuId'] == $val['goods_sku']) {
                    $params['结果'] = $v['reason'];
                }
            }
            $log_data[$key]['params'] = json_encode($params, JSON_UNESCAPED_UNICODE);
        }
        $priceLogDb->saveAll($log_data);


        Cache::clear('goods');
        Cache::clear('sale_price');
        $this->layuiReturn($result['priceList'], 1, '提交成功', 1);
    }

    public function postjunlog($goods_sku)
    {
        $junapidb = new Junapidb();
        $get_junApi = $junapidb->where('goods_sku', $goods_sku)->order('junapi_id desc')->select();
        foreach ($get_junApi as $key => $val) {
            $get_junApi[$key]['result_arr'] = json_decode($val['result_json'], true);
        }
        $this->assign('get_jun', $get_junApi);
        return $this->fetch();
    }

    protected function junPush($goods_sku, $price = 0, $stock = 0)
    {
        // 军采 如果审核通过 推送商品
        $goodsdb = new Goodsdb ();
        $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $goods_sku)->find();
        $post_json = array();
        $post_json_price ['priceList'] = array();
        if ($get_goods) {
            $get_goods->save(['jun_last_stock' => $stock, 'jun_last_time' => time()]);// 获取最后推送库存和最后推送时间
            $get_goods = $get_goods->toArray();
            if ($get_goods ['is_push'] == 1) {
                // 修改
                /*
                 * $temp ['sku'] = $goods_sku;
                 * $temp ['updateType'] = 2;
                 * array_push ( $post_json, $temp );
                 * $temp ['sku'] = $goods_sku;
                 * $temp ['updateType'] = 3;
                 * array_push ( $post_json, $temp );
                 */
                if ($get_goods ['callet_juncai'] == 2) {
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 4;
                    array_push($post_json, $temp);
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 5;
                    array_push($post_json, $temp);
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 6;
                    array_push($post_json, $temp);
                }
            } else {
                $goodsdb->where('goods_sku', $goods_sku)->update([
                    'is_push' => 1
                ]);
                if ($get_goods ['callet_juncai'] == 2) {
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 1;
                    array_push($post_json, $temp);
                }
            }
            // 报价
            $temp_price = array();
            $temp_price ['sku'] = $goods_sku;
            $temp_price ['price'] = $price;
            $temp_price ['stock'] = $stock;
            $temp_price['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $get_goods ['goods_id'];
            $temp_price['eccode'] = $get_goods ['goods_id'];
            $temp_price['linkprice'] = Db::name('sale_price')->where('goods_sku', $get_goods['goods_sku'])->value('sale_price');
            array_push($post_json_price ['priceList'], $temp_price);
        }
        $jun_api = new Api ();
        if (count($post_json) > 0) {
            $return_json = $jun_api->ajaxproductupdateinfo($post_json);
            $junapidb = new Junapidb ();
            $junapidb->param ['goods_sku'] = $goods_sku;
            $junapidb->param ['send_json'] = $post_json;
            $junapidb->param ['result_json'] = $return_json;
            $junapidb->ajaxSave();
        }
        return $post_json_price;
        $return_price = $jun_api->ajaxCountPrice($post_json_price);
        // print_r($return_json);
        // print_r($return_price);
        $junapidb = new Junapidb ();
        $junapidb->param ['goods_sku'] = $goods_sku;
        $junapidb->param ['send_json'] = $post_json_price;
        $junapidb->param ['result_json'] = $return_price;
        $junapidb->ajaxSave();
    }

    public function saveData()
    {
        if ($this->post ['callet_juncai'] == 1) {
            $return = $this->db->ajaxSaveJuncai();
        } else {
            $return = $this->db->ajaxSave();
        }
        if ($return != 'success') {
            $this->layuiReturn($return, 0, $return, -1);
        } else {
            $text = isset($this->db->jun_push_result['priceList']) && $this->db->jun_push_result['priceList'][0]['issuccess'] == 'false' ? $this->db->jun_push_result['priceList'][0]['reason'] : '推送成功';
            $this->layuiReturn($this->db->last_goods_sku, 1, $text);
        }
    }

    public function saveDataHenan()
    {
        $return = $this->db->ajaxUpdateHenan();
        if ($return != 'success') {
            $this->layuiReturn($this->db->last_goods_sku, 0, $return, -1);
        } else {
            $this->layuiReturn($this->db->last_goods_sku, 1, 'success', 1);
        }
    }

    /**
     *
     * @todo 软删除
     */
    public function ajaxDelete()
    {
        $this->db->param = $this->post;
        $this->db->ajaxDelete();
        $this->layuiReturn('删除成功', 0);
    }

    public function ajaxDown()
    {
        $where ['goods_id'] = array(
            'IN',
            $this->post ['goods_id']
        );
        $data ['sale_state'] = 2;
        $this->db->aloneSave($data, $where);
        $this->layuiReturn('保存成功');
    }

    public function ajaxUp()
    {
        $where ['goods_id'] = array(
            'IN',
            $this->post ['goods_id']
        );
        $data ['sale_state'] = 1;
        $this->db->aloneSave($data, $where);
        $this->layuiReturn('保存成功');
    }

    public function upload()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $get_col_num = $sheet->getHighestColumn(); // 总列
                $phpexcel_shared_date = new \PHPExcel_Shared_Date ();
                $data = array();
                $text = '';
                $categorydb = new Categorydb ();
                $branddb = new Branddb ();
                $attrdb = new Attrdb ();
                for ($i = 2; $i <= $get_row_num; $i++) {
                    unset ($temp);
                    $temp ['flag_i'] = $i;
                    $the_sheet = $objPHPExcel->getActiveSheet();
                    $temp ['category_name'] = $this->getSheetValue($the_sheet, "A" . $i);
                    $temp ['brand_name'] = $this->getSheetValue($the_sheet, "B" . $i);
                    $temp ['goods_name'] = $this->getSheetValue($the_sheet, "C" . $i);
                    $temp ['goods_son_name'] = $this->getSheetValue($the_sheet, "D" . $i);
                    $temp ['goods_model'] = $this->getSheetValue($the_sheet, "E" . $i);
                    $goods_sku = $this->getSheetValue($the_sheet, "F" . $i);
                    $temp ['goods_sku'] = $goods_sku ? $goods_sku : 'UTEC' . base_convert(uniqid(), 16, 10);
                    $temp ['weight'] = 0;
                    $temp ['goods_unit'] = $this->getSheetValue($the_sheet, "G" . $i);
                    $temp ['goods_keywords'] = $this->getSheetValue($the_sheet, "H" . $i);
                    $temp ['goods_intro'] = $this->getSheetValue($the_sheet, "I" . $i);
                    $temp ['goods_pictures'] = str_replace(';', ',', $this->getSheetValue($the_sheet, "J" . $i));
                    $temp ['sale_attr_price_name'] [0] = '商品价格';
                    $temp ['market_price'] [0] = $this->getSheetValue($the_sheet, "K" . $i);
                    $temp ['sale_price'] [0] = $this->getSheetValue($the_sheet, "L" . $i);
                    $api_price = $this->getSheetValue($the_sheet, "M" . $i);
                    $temp ['api_price'] [0] = $api_price ? $api_price : $temp ['sale_price'] [0];
                    $score = $this->getSheetValue($the_sheet, "N" . $i);
                    $temp ['give_score'] [0] = $score ? $score : 0;
                    $stock = $this->getSheetValue($the_sheet, "O" . $i);
                    $temp ['view_stock'] [0] = $stock ? $stock : 10;
                    $temp ['goods_attr'] = $this->getSheetValue($the_sheet, "P" . $i);
                    $temp ['goods_content'] = $this->getSheetValue($the_sheet, "Q" . $i);
                    $is_install = $this->getSheetValue($the_sheet, "R" . $i);
                    $temp ['is_install'] = $is_install == '是' ? 1 : 2;
                    $sale_state = $this->getSheetValue($the_sheet, "S" . $i);
                    $temp ['sale_state'] = $sale_state == '是' ? 1 : 2;
                    $is_copy = $this->getSheetValue($the_sheet, 'T' . $i);
                    $temp ['is_copy'] = $is_copy == '是' ? 1 : 2;
                    // 验证必填
                    if ($temp ['category_name'] == '' || $temp ['brand_name'] == '' || $temp ['goods_name'] == '' || $temp ['goods_model'] == '' || $temp ['goods_unit'] == '' || $temp ['market_price'] == '' || $temp ['sale_price'] == '') {
                        $this->layuiReturn('导入失败', 0, '红色的不能为空，请检查excel第' . $i . '行', 0);
                    }
                    // 验证重复
                    foreach ($data as $k => $v) {
                        if ($v ['goods_name'] == $temp ['goods_name']) {
                            $this->layuiReturn('导入失败', 0, '商品名称重复，请检查excel第' . $i . '行', 0);
                        }
                        if ($temp ['goods_sku'] != '' && $v ['goods_sku'] == $temp ['goods_sku']) {
                            $this->layuiReturn('导入失败', 0, '商品编号重复，请检查excel第' . $i . '行', 0);
                        }
                        if ($v ['goods_model'] == $temp ['goods_model']) {
                            $this->layuiReturn('导入失败', 0, '商品型号重复，请检查excel第' . $i . '行', 0);
                        }
                    }
                    // 验证分类是否存在
                    $categorydb->param ['category_sign'] = $temp ['category_name'];
                    $categorydb->param ['level'] = 3;
                    $chk_category = $categorydb->ajaxTreeFind($temp ['category_name']);
                    if (!$chk_category) {
                        $this->layuiReturn('导入失败', 0, '商品分类不存在，请检查excel第' . $i . '行', 0);
                    } else {
                        $temp ['category_sign1'] = $chk_category ['category_sign1'];
                        $temp ['category_sign2'] = $chk_category ['category_sign2'];
                        $temp ['category_sign3'] = $chk_category ['category_sign3'];
                    }
                    // 验证品牌是否存在
                    $chk_brand = $branddb->chkFind($temp ['brand_name']);
                    if (!$chk_brand) {
                        $this->layuiReturn('导入失败', 0, '商品品牌不存在，请检查excel第' . $i . '行', 0);
                    } else {
                        $temp ['brand_sign'] = $chk_brand ['brand_sign'];
                    }
                    // 验证属性是否存在
                    if ($temp ['goods_attr']) {
                        $get_attr_arr = explode(';', $temp ['goods_attr']);
                        foreach ($get_attr_arr as $k1 => $v1) {
                            $t1 = explode(':', $v1);
                            if (count($t1) != 2) {
                                $this->layuiReturn('导入失败', 0, '商品属性格式不正确，请检查excel第' . $i . '行', 0);
                            }
                            $attrdb->param ['category_sign'] = $temp ['category_sign3'];
                            $attrdb->param ['attr_name'] = $t1 [0];
                            $chk_attr = $attrdb->ajaxChkFind();
                            if (!$chk_attr) {
                                $this->layuiReturn('导入失败', 0, '商品属性（' . $t1 [0] . '）不存在，请检查excel第' . $i . '行', 0);
                            } else {
                                $temp [$chk_attr ['attr_sign']] = $t1 [1];
                            }
                        }
                    }
                    array_push($data, $temp);
                }
                $this->db->param = $data;
                $return = $this->db->ajaxSaveAll();
                if ($return == 'success') {
                    $this->layuiReturn('导入成功', 0, '导入成功', 1);
                } else {
                    $this->layuiReturn('导入失败', 0, $return, 0);
                }
            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
            }
        }
    }

    public function transfer()
    {
        if (!isset ($this->post ['category_sign1']) || !isset ($this->post ['category_sign2']) || !isset ($this->post ['category_sign3']) || !isset ($this->post ['goods_arr'])) {
            $this->layuiReturn('参数错误', 0, '参数错误', 0);
        }
        $category_sign1 = $this->post ['category_sign1'];
        $category_sign2 = $this->post ['category_sign2'];
        $category_sign3 = $this->post ['category_sign3'];
        $goods_ids = $this->post ['goods_arr'];
        if ($category_sign1 == '' || $category_sign2 == '' || $category_sign3 == '' || $goods_ids == '') {
            $this->layuiReturn('参数错误', 0, '参数错误', 0);
        }
        $this->db->ajaxTransfer($category_sign1, $category_sign2, $category_sign3, $goods_ids);
        $this->layuiReturn('数据转移成功', 1, '数据转移成功', 1);
    }

    public function siteData()
    {
        if (!isset ($this->post ['goods_sku'])) {
            exit ('参数错误');
        }
        $this->db->param ['site_id'] = -1;
        $this->db->param ['goods_sku'] = $this->post ['goods_sku'];
        $this->db->param ['page'] = 1;
        $this->db->param ['limit'] = 50;
        $this->db->param ['_o'] = 'site_id';
        $this->db->param ['_b'] = 'desc';
        $data = $this->db->ajaxList();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function saveSitePriceInfo()
    {
        if (!isset ($this->post ['sale_price_sign']) || !isset ($this->post ['value']) || !isset ($this->post ['field']) || !isset ($this->post ['goods_sku'])) {
            $this->layuiReturn('参数错误', 0, '参数错误', 0);
        }
        $this->db->param ['goods_sku'] = $this->post ['goods_sku'];
        $this->db->param ['site_id'] = $this->post ['site_id'];
        if ($this->post ['field'] != 'sale_state') {
            $get_goods_info = $this->db->ajaxFind();
            $salePricedb = new SalePricedb ();
            $salePricedb->param ['site_id'] = $this->post ['site_id'];
            $salePricedb->param ['sale_price_sign'] = $this->post ['sale_price_sign'];
            $salePricedb->param ['goods_sku'] = $this->post ['goods_sku'];
            $salePricedb->param ['field'] = $this->post ['field'];
            $salePricedb->param ['value'] = $this->post ['value'];
            $salePricedb->param ['category_sign3'] = $get_goods_info ['category_sign3'];
            $chk_return = $salePricedb->ajaxSaveFieldValue();
            $return = $salePricedb->ajaxFind();
            $this->db->writePriceRecord($this->post ['goods_sku']);
            $this->layuiReturn($return, 1, '数据保存成功', 1);
        } else {
            $this->db->ajaxSaveOne($this->post ['field'], $this->post ['value']);
            $this->layuiReturn('数据保存成功', 1, '数据保存成功', 1);
        }
    }

    public function chkModel()
    {
        $this->post['goods_model'] = $this->post['value'];
        $this->post['partner_id'] = PARTNER_ID;
        $this->post['site_id'] = SITE_ID;
        $chk_goods = Goodsdb::where('site_id', SITE_ID)
            ->where('partner_id', PARTNER_ID)
            ->where('goods_model', trim($this->post['value']))
            ->where('goods_sku', '<>', $this->post['goods_sign'])
            ->find();
        if ($chk_goods) {
            $this->layuiReturn('', 1, '商品型号已被使用', 1);
        } else {
            $this->layuiReturn('', 0, '商品型号可使用', 0);
        }
//        $get_goods = Goodsdb::where('goods_sku', $this->post['goods_sign'])->find();
//        $this->post['category_sign3'] = $get_goods['category_sign3'];
//        $goodsrule = new Goodsrule();
//        $chk = $goodsrule->scene('checkmodel')->check($this->post);
//        if ($chk) {
//            $this->layuiReturn('', 0, '商品型号可使用', 0);
//        } else {
//            $this->layuiReturn('', 1, '商品型号已被使用', 1);
//        }
//		if (! isset ( $this->post ['value'] ) || ! isset ( $this->post ['goods_sign'] )) {
//			$this->layuiReturn ( '参数错误', 0, '参数错误', 0 );
//		}
//		$this->db->param ['goods_model'] = $this->post ['value'];
//		$this->db->param ['model_exact'] = 'yes';
//		$get_goods_info = $this->db->chkGoodsModel ();
//		if (count ( $get_goods_info ) > 0) {
//			if ($get_goods_info ['goods_sku'] == $this->post ['goods_sign']) {
//				$this->layuiReturn ( '', 0, '当前商品型号正常，可以修改数据', 2 );
//			} else {
//				$this->layuiReturn ( $get_goods_info, 1, '商品型号已存在（商品编号：' . $get_goods_info ['goods_sku'] . '）', 1 );
//			}
//		} else {
//			$this->layuiReturn ( '', 0, '商品型号没有被录入', 0 );
//		}
    }

    public function exportCgGoods()
    {
        set_time_limit(0);
        $count = $this->db->ajaxCount();
        $this->db->param ['page'] = 1;
        $this->db->param ['limit'] = $count;
        $this->db->param ['pre_info'] = 'jun';
        $data = $this->db->ajaxList();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '产品' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '一级分类',
            '二级分类',
            '三级分类',
            '品牌名称',
            '商品名称',
            '商品编号',
            '参考价（元）',
            '图片'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        foreach ($data as $key => $val) {
            $temp = array(
                $val ['category_name1'],
                $val ['category_name2'],
                $val ['category_name'],
                $val ['jun_brand_name'],
                $val ['goods_name'],
                $val ['goods_sku'],
                $val ['sale_price'],
                $val ['goods_picture'] ['save_path']
            );
            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    public function exportGoods()
    {
        set_time_limit(0);
        $count = $this->db->ajaxCount();
        $this->db->param ['page'] = 1;
        $this->db->param ['limit'] = $count;
        $data = $this->db->ajaxList();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '产品' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array();
        foreach ($this->cols as $key => $val) {
            if (isset ($val ['title']) && isset ($val ['field']) && $key != 0 && $key != count($this->cols)) {
                array_push($header_data, $val ['title']);
            }
        }
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        foreach ($data as $key => $val) {
            $temp = array();
            foreach ($this->cols as $k => $v) {
                if (isset ($v ['title']) && isset ($v ['field']) && $k != 0 && $k != count($this->cols)) {
                    switch ($v ['field']) {
                        case 'goods_picture' :
                            $temp [] = $val ['goods_picture'] ['save_path'];
                            break;
                        case 'goods_pictures' :
                            $temp [] = $val ['goods_pictures'] ['save_path'];
                            break;
                        case 'audit_state' :
                            if ($val ['audit_state'] == 1) {
                                $temp [] = '已审核';
                            } elseif ($val ['audit_state'] == 0) {
                                $temp [] = '等待审核';
                            } else {
                                $temp [] = '驳回审核';
                            }
                        default :
                            if ($val [$v ['field']] === TRUE) {
                                $temp [] = '是';
                            } elseif ($val [$v ['field']] === FALSE) {
                                $temp [] = '否';
                            } else {
                                $temp [] = $val [$v ['field']];
                            }
                            break;
                    }
                }
            }
            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    public function downExcel($excel_name)
    {
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
            } else {
                $cell_value = chr($start + $i) . '1';
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension(chr($start + $i))->setWidth(20);
        }
    }

    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
    }

    /**
     * Title("校验今日报价商品")
     */
    public function chkTodayBaojia()
    {
        $data = Db::name('goods_price_log')
            //->fetchSql(true)
            ->whereIn('goods_sku', $this->post['goods_sku_arr'])
            ->whereIn('types', ['供应商报价', '军采统一报价', '产品详情报价', '同步军网报价', '报价审核', '自动推送下架'])
            ->whereTime('date', 'today')
            ->whereLike('params', '%"结果":"入库成功"%')
            ->group('goods_sku')
            ->field('count(*) count,goods_sku')
            ->select();
        $this->layuiReturn($data);
    }

    /**
     * Title("军网下架")
     */
    public function junDown()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $the_sheet = $objPHPExcel->getActiveSheet();
                $info_arr = [];
                for ($i = 2; $i <= $get_row_num; $i++) {
                    $temp = [];
                    $temp['sku'] = (string)$this->getSheetValue($the_sheet, "A" . $i);
                    $temp['updateType'] = 5;
                    array_push($info_arr, $temp);
                }
                if (count($info_arr)) {
                    $junApi = new Api();
                    $junApi->ajaxproductupdateinfo($info_arr);
                    $this->layuiReturn('提交成功,正在生成', 0, '提交成功,正在生成', 1);
                } else {
                    $this->layuiReturn('导入订单错误', 0, '导入订单错误', 2);
                }

            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 2);
            }
        }
    }

    /**
     * Title("导入自选库商品")
     */
    public function importGoods()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        $all_data = [];
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName);
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $the_sheet = $objPHPExcel->getActiveSheet();
                $all_data = [];
                $price_data = [];
                for ($i = 2; $i <= $get_row_num; $i++) {
                    $temp = [];
                    $temp['goods_name'] = $this->getSheetValue($the_sheet, "A" . $i);
                    $temp['category_sign1'] = $this->getSheetValue($the_sheet, "B" . $i) ?: 'cb879747851c8d1042f680fb0d2da49f';
                    $temp['category_sign2'] = $this->getSheetValue($the_sheet, "C" . $i) ?: '3752be6b5dc81d4ef1c2bbd8716ff74f';
                    $temp['category_sign3'] = $this->getSheetValue($the_sheet, "D" . $i) ?: 'a96051f3ecceaca2dc8d4c4b3e63fa27';
                    $temp['brand_sign'] = $this->getSheetValue($the_sheet, "E" . $i) ?: '0e9a637e8170b5fc514f07ff85884b7f';
                    $temp['goods_model'] = $this->getSheetValue($the_sheet, 'F' . $i);
                    $temp['goods_son_name'] = $this->getSheetValue($the_sheet, 'G' . $i);
                    $temp['upc'] = $this->getSheetValue($the_sheet, 'H' . $i);
                    $temp['ziying_url'] = $this->getSheetValue($the_sheet, 'I' . $i);
                    $temp['goods_unit'] = $this->getSheetValue($the_sheet, "J" . $i) ?: '件';
                    $temp['goods_keywords'] = $this->getSheetValue($the_sheet, "K" . $i) ?: 0.13;
                    $temp['code_69'] = $this->getSheetValue($the_sheet, "L" . $i);
                    $temp['packing_list'] = $this->getSheetValue($the_sheet, "M" . $i);
                    $temp['sale_price'] = $this->getSheetValue($the_sheet, "O" . $i);
                    $temp['api_price'] = $this->getSheetValue($the_sheet, "P" . $i) ?: $temp['sale_price'];
                    $temp['view_stock'] = $this->getSheetValue($the_sheet, 'Q' . $i) ?: 999;
                    // 默认值
                    $temp['goods_sku'] = 'SKU' . base_convert(uniqid(), 16, 10);
                    $temp['is_zhongdian'] = 0;
                    $temp['good_type'] = 0;
                    $temp['fenlei_name'] = Db::name('category')->where('brand_sign', $temp['category_sign3'])->value('category_name');
                    $temp['pinpai_name'] = Db::name('brand')->where('brand_sign', $temp['brand_sign'])->value('brand_name');
                    $temp['admin_id'] = MEMBER_ID;
                    $temp['partner_id'] = 25;
                    $temp['site_id'] = 117;
                    $temp['create_time'] = time();

                    $temp_price = [];
                    $temp_price['partner_id'] = 25;
                    $temp_price['site_id'] = 117;
                    $temp_price['create_time'] = time();
                    $temp_price['goods_sku'] = $temp['goods_sku'];
                    $temp_price['market_price'] = $this->getSheetValue($the_sheet, 'N' . $i) ?: $temp['sale_price'];
                    $temp_price['sale_price'] = $temp['sale_price'];
                    $temp_price['api_price'] = $temp['api_price'];
                    $temp_price['view_stock'] = $temp['view_stock'];
                    $temp_price['sale_attr_price_name'] = '商品价格';
                    $temp_price['sale_price_sign'] = md5(time() . uniqid());
                    $temp_price['caigoujia'] = $this->getSheetValue($the_sheet, 'R' . $i);
                    $temp_price['huoyuan'] = $this->getSheetValue($the_sheet, 'S' . $i);
                    array_push($all_data, $temp);
                    array_push($price_data, $temp_price);
                }
                if(count($all_data) == 0){
                    $this->layuiReturn('没有可导入数据', 0, '没有可导入数据', 0);
                }
                $this->layuiReturn('同步完成', 0, '同步完成', 1);
            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
            }
        }
    }
}
